package com.zy.baselib.widget

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.drawable.Drawable

/**
 * 重写ImageSpan
 * 可以设置Image 垂直方向
 * top/center/bottom
 * @author shalei
 */
class ImageSpan(drawable: Drawable, verticalAlignment: Int) :
    android.text.style.ImageSpan(drawable, verticalAlignment) {

    companion object {
        const val ALIGN_TOP = 0
        const val ALIGN_BOTTOM = 1
        const val ALIGN_CENTER = 2
    }

    constructor(drawable: Drawable) : this(drawable, ALIGN_CENTER)

//    override fun getSize(
//        paint: Paint,
//        text: CharSequence?,
//        start: Int,
//        end: Int,
//        fm: Paint.FontMetricsInt?
//    ): Int {
//        val d = drawable
//        val rect: Rect = d.bounds
//        if (fm != null) {
//            val fmPaint: Paint.FontMetricsInt = paint.fontMetricsInt
//            val fontHeight: Int = fmPaint.bottom - fmPaint.top
//            val drHeight: Int = rect.bottom - rect.top
//            val top = drHeight / 2 - fontHeight / 4
//            val bottom = drHeight / 2 + fontHeight / 4
//            fm.ascent = -bottom
//            fm.top = -bottom
//            fm.bottom = top
//            fm.descent = top
//        }
//        return rect.right
//    }

    override fun draw(
        canvas: Canvas,
        text: CharSequence?,
        start: Int,
        end: Int,
        x: Float,
        top: Int,
        y: Int,
        bottom: Int,
        paint: Paint
    ) {
        val b = drawable
        canvas.save()
        val transY = when (verticalAlignment) {
            ALIGN_CENTER -> ((bottom - top) - b.bounds.bottom) / 2 + top
            ALIGN_TOP -> top
            ALIGN_BOTTOM -> bottom - b.bounds.bottom
            else -> bottom - b.bounds.bottom
        }
        canvas.translate(x, transY.toFloat())
        b.draw(canvas)
        canvas.restore()
    }

}